package com.leyou.order.utils;

import com.github.wxpay.sdk.WXPay;
import com.github.wxpay.sdk.WXPayConfigImpl;
import com.github.wxpay.sdk.WXPayConstants;
import com.github.wxpay.sdk.WXPayUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * @author 虎哥
 */
@Slf4j
@Component
public class PayHelper {

    private WXPay wxPay;

    private WXPayConfigImpl payConfig;

    public PayHelper(WXPay wxPay, WXPayConfigImpl payConfig) {
        this.wxPay = wxPay;
        this.payConfig = payConfig;
    }

    public String getPayUrl(Long orderId, Long totalPay, String desc) {
        // 6个请求参数：
        Map<String, String> data = new HashMap<String, String>();
        // 商品描述
        data.put("body", desc);
        // 订单编号
        data.put("out_trade_no", orderId.toString());
        // 订单金额
        data.put("total_fee", totalPay.toString());
        // 终端IP
        data.put("spbill_create_ip", payConfig.getSpbillCreateIp());
        // 微信回调通知的地址
        data.put("notify_url", payConfig.getNotifyUrl());
        // 支付类型
        data.put("trade_type", payConfig.getTradeType());

        try {
            // 发请求，获取结果
            Map<String, String> resp = wxPay.unifiedOrder(data);

            checkSignature(resp);

            // 获取支付链接
            String url = resp.get("code_url");
            if (StringUtils.isBlank(url)) {
                throw new RuntimeException("支付链接为空！");
            }
            return url;
        } catch (Exception e) {
            log.error("获取支付链接失败，原因：{}", e.getMessage());
            throw new RuntimeException(e);
        }
    }

    public void checkSignature(Map<String, String> resp){
        try {
            // 验证签名
            boolean boo = WXPayUtil.isSignatureValid(resp, payConfig.getKey(), WXPayConstants.SignType.MD5);
            boolean boo2 = WXPayUtil.isSignatureValid(resp, payConfig.getKey(), WXPayConstants.SignType.HMACSHA256);
            if(!boo && !boo2){
                throw new RuntimeException("签名验证失败，再捣乱我就报警了!");
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
